package com.java.web;

import com.java.dao.commDao;
import com.java.dao.commDaoImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @Author xyd
 * @Date 2021/12/23 22:36
 * @Version 1.0
 */
public class addProductServlet extends HttpServlet {

    private commDao commDao = new commDaoImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("收到请求");
        String imageUrl = "";
        String[] str = new String[6];
        //获取图片
        //先判断上传的数据是否是多段

        if (ServletFileUpload.isMultipartContent(request)) {

            //创建工厂实现类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            //创建用于解析上传数据的工具类
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            String path0 = request.getRealPath("temp");
            System.out.println(path0);
            try {
                List<FileItem> list = servletFileUpload.parseRequest(request);

                //循环判断每一个表单项是普通类型还是上传的文件
                int i = 0;
                for (FileItem fileItem : list) {
                    if (fileItem.isFormField()) {
                        str[i++] = fileItem.getString("UTF-8");
                        System.out.println("添加成个");
                    } else {
//                        System.out.println(fileItem.getFieldName());
                        fileItem.write(new File(path0+"\\"+fileItem.getName()));
                        imageUrl ="/temp/"+fileItem.getName();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            System.out.println(Arrays.toString(str));

            //commDao.updateComm(Integer.parseInt(str[0]), str[1], Integer.parseInt(str[2]), Integer.parseInt(str[3]), str[4], str[5], imageUrl);
            commDao.insertComm(str[0], Integer.parseInt(str[1]), Integer.parseInt(str[2]), str[3], str[4], imageUrl);
            request.setAttribute("err","<h4><font color='green'>添加成功!</font></h4>");
            request.getRequestDispatcher("/admin/products/list.jsp").forward(request, response);
        }
    }
}